// 假设HTML中有id为'messageInput'的输入框和id为'messageHistory'的显示区域

function createMessageElement(timestamp, text) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    messageElement.innerHTML = `<span class="timestamp">${timestamp}</span>: ${text}`;
    return messageElement;
}

function appendMessageToHistory(messageElement) {
    const messageHistory = document.getElementById('chatHistory');
    messageHistory.appendChild(messageElement);
}

function saveMessageToLocalStorage(timestamp, text) {
    const messages = JSON.parse(localStorage.getItem('messages')) || [];
    messages.push({ timestamp, text });
    localStorage.setItem('messages', JSON.stringify(messages));
}

async function postMessageToServer(messageText) {
    try {
        const response = await fetch('http://localhost:3000/messages', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message: messageText })
        });

        if (!response.ok) {
            throw new Error('Failed to post message: ' + response.status);
        }

        const serverResponse = await response.json();
        console.log('Server response:', serverResponse);
    } catch (error) {
        console.error('Error posting message:', error);
    }
}

function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const messageText = messageInput.value.trim();

    if (messageText) {
        const timestamp = new Date().toLocaleString();
        const messageElement = createMessageElement(timestamp, messageText);
        appendMessageToHistory(messageElement);
        postMessageToServer(messageText); // 发送消息到服务器
        saveMessageToLocalStorage(timestamp, messageText); // 可选，保存到localStorage
        messageInput.value = ''; // 清空输入框
    } else {
        alert('请输入消息内容！');
    }
}

// 绑定发送按钮的点击事件（假设HTML中有id为'messageInput'的按钮）
document.getElementById('messageInput').addEventListener('click', sendMessage);